/*
 *******************************************************************
 *
 * COPYRIGHT (coffee) 2013 - 2014 LTV Co., Ltd  All rights reserved
 *
 * Created  : Mar 9, 2014
 * Change History
 * =================================================================
 * DATE                DEVELOPER        REVISION      DESCRIPTION
 * =================================================================
 * Mar 9, 2014        Steven        1.0           First Created.
 * =================================================================
 *
 *
 *******************************************************************/
/**
 * 
 */
package vn.com.ltv.lo;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import vn.com.ltv.lo.common.Constants;
import vn.com.ltv.lo.common.Decrypter;
import vn.com.ltv.lo.common.DialogUtil;
import vn.com.ltv.lo.common.SessionManager;
import vn.com.ltv.lo.daos.UserDAO;
import vn.com.ltv.lo.dtos.UserDTO;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * @author Steven
 *
 */
public class LoginActivity extends Activity implements View.OnClickListener{
	
	//-----------Define variables---------------
	EditText edtEmail,edtPass;
	CheckBox cbxShowpass;
	Button btnLogin;
	TextView tvRegister;
	LinearLayout lnRegister;
	
	String sEmail,sPassword;
	String err = "";
	
	// Session Manager Class
    SessionManager session;
    	
	
	//-----------Request Service---------------
	private HttpClient client = new DefaultHttpClient();		                
	private HttpResponse response;
	private JSONObject json = new JSONObject();
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		init();
		//----------------------------------
		
		//-----------Actions---------------
		btnLogin.setOnClickListener(this);
		lnRegister.setOnClickListener(this);
		
		cbxShowpass.setOnCheckedChangeListener(new OnCheckedChangeListener() {			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (!cbxShowpass.isChecked()) {
					edtPass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
				} else {
					edtPass.setInputType(InputType.TYPE_CLASS_TEXT);
				}
			}
		});
		
	}
	
	//-----------Initial variables---------------
	private void init(){
		edtEmail = (EditText)findViewById(R.id.login_edtEmail);
		edtPass = (EditText)findViewById(R.id.login_edtPass);
		cbxShowpass = (CheckBox)findViewById(R.id.login_cbxShowpass);
		btnLogin = (Button)findViewById(R.id.login_btnLogin);
		tvRegister = (TextView)findViewById(R.id.login_tvRegister);
		lnRegister = (LinearLayout)findViewById(R.id.login_lnRegister);
		session = new SessionManager(LoginActivity.this); 
		tvRegister.setPaintFlags(tvRegister.getPaintFlags() |   Paint.UNDERLINE_TEXT_FLAG);
		edtEmail.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
		
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		//----------textview register is clicked----------
		case R.id.login_lnRegister:
			intent = new Intent(LoginActivity.this,RegisterActivity.class);
			startActivity(intent);
			break;
		
		//----------button register is clicked----------
		case R.id.login_btnLogin:
			err = "";
			sEmail = edtEmail.getText().toString().trim();
			sPassword = edtPass.getText().toString().trim();				
			
			checkData();
							
			if (err.equals("")) {
				if (login()) {
					session.createLoginSession("", sEmail);
					intent = new Intent(LoginActivity.this, Home.class);
					startActivity(intent);						
				} else {
					DialogUtil.CreateDialog(LoginActivity.this, Constants.ERR_LOGIN_REQUEST);
					DialogUtil.dialog.show();
				}				
				
			} else {
				DialogUtil.CreateDialog(LoginActivity.this, err);
				DialogUtil.dialog.show();
			}
			break;

		default:
			break;
		}
		
	}
	
	private boolean checkData(){
		//----------check empty fields--------------
		if (sEmail.equals("")) {
			err = "Email is empty !";
			return false;
		}else{
			if (sPassword.equals("")) {
				err = "Password is empty !";
				return false;
			}
		}
		
		//--------check validate value input----------
//		if (!Validate.validateEmail(sEmail)) {
//			err = "Email is not validate !";
//			return false;
//		} else {
//			if (!Validate.validatePassword(sPassword)) {
//				err = "Password is not validate !";
//				return false;
//			}
//		}
		
		return true;
	}
	
	private boolean login(){
//		try {
//		Decrypter decrypter = new Decrypter();
//        HttpPost post = new HttpPost("http://ltv.com.vn/e4u/api/login");
//        json.put("email", decrypter.encrypt(sEmail));
//        json.put("password", decrypter.encrypt(sPassword));
//        StringEntity se = new StringEntity( json.toString());  
//        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
//        post.setEntity(se);
//        response = client.execute(post);
//
//        /*Checking response */
//        if(response!=null){
//            InputStream in = response.getEntity().getContent(); //Get the data in the entity
//        }
//
//    } catch(Exception e) {
//    	return false;
//    }
		
		Decrypter decrypter;
		try {
			decrypter = new Decrypter();
			UserDTO userDTO = new UserDTO();
			UserDAO userDAO = new UserDAO(LoginActivity.this);
			userDTO = userDAO.get(decrypter.encrypt(sEmail));
			if (decrypter.encrypt(sEmail).equals(userDTO.getUsrEml()) 
					&& decrypter.encrypt(sPassword).equals(userDTO.getUsrPwd())) {
				return true;
			}
		} catch (Exception e) {			
			return false;
		}
			
		return false;
	}
	


}
